use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use serde_json::{Map, Value};
use tracing::{debug, info};
use crate::http::get_gio;
use crate::http::http_request::{HttpMethod, HttpRequest};
use crate::http::http_response::HttpResponse;
use crate::template_engine::template_engine::TemplateEngine;
use crate::util::date_util;

pub fn template_handler(request: &HttpRequest, response: &mut HttpResponse) {


   // 读取 public/template/index.html 文件
   let template_path = Path::new("public/resources/template/index.html");
   let display = template_path.display();
   info!("Index handler for {}", template_path.display());

   let mut file = match File::open(&template_path) {
      Ok(file) => file,
      Err(why) => panic!("couldn't open {}: {:?}", display, why),
   };

   let mut template_content = String::new();
   if let Err(_) = file.read_to_string(&mut template_content) {
      HttpResponse::not_found(response);
   }
   info!("index.html raw: {}", template_content);


   // 准备模板数据
   let mut data = HashMap::new();


   let gio = get_gio().read().expect("拿不到锁");

   if let Some(messages) = gio.get("messages") {

      let mut messges_value: Vec<Map<String, Value>> = serde_json::from_str(messages).unwrap();
      debug!("template_handler messges_value: {:?}", messges_value);
      data.insert("messages".to_string(), messges_value);
   }

   debug!("template_handler data: {:?}", data);

   // 使用模板引擎解析模板
   let rendered_content = TemplateEngine::render(&template_content, &data);

   info!("index.html parse: {}", template_content);


   let mut headers = &mut response.headers;

   headers.insert("Content-Type".to_string(), "text/html".to_string());
   headers.insert("Content-Length".to_string(), rendered_content.len().to_string());
   headers.insert("Connection".to_string(), "keep-alive".to_string());
   headers.insert("Server".to_string(), "Rust".to_string());

   HttpResponse::common_headers(&mut headers);

   response.body = rendered_content.into_bytes();

    // 尝试读取 public 文件夹下的图标文件
   HttpResponse::ok(response);

} 